<template>
	<view class="cate-box">
		<!-- 左侧分类 -->
		<scroll-view scroll-y class="left">
			<view v-for="category in categories" :key="category._id"
				:class="['left-text', (activeCategoryId === category._id) ? 'active' : '']"
				@tap="handleCategoryTap(category)">
				{{ category.name }}
			</view>
		</scroll-view>

		<!-- 右侧商品 -->
		<scroll-view scroll-y class="right" @scrolltolower="handleScrollToLower">
			<view class="right-box">
				<view v-if="filteredGoods.length === 0" class="empty-state">
					<image src="/static/avatar/empty.png" mode="aspectFit" class="empty-image"></image>
					<text class="empty-text">此分类没有物品</text>
				</view>
				<view v-for="goods in filteredGoods" :key="goods._id" class="goods-box" @tap="goodsclick(goods)">
					<view class="img-box">
						<image class="goods-img" :src="goods.thumb || thumb" mode="aspectFill"></image>
					</view>
					<view class="goods-info">
						<view class="goods-title">{{ goods.name }}</view>
						<view class="goods-desc">
							<text class="desc-text" v-if="goods.brand">{{ goods.brand }}</text>
							<text class="desc-text" v-if="goods.model">{{ goods.model }}</text>
						</view>
						<view class="goods-desc">
							<text class="" v-if="goods.note">{{ goods.note }}</text>
						</view>
						<view class="goods-price-cart">
							<view class="goods-price">库存：{{ goods.remain_count }}</view>
							<view class="product-handle" v-if="showplus">
								<image src="@/uni_modules/cy-cate/static/icon-minus.png"
									@tap.stop="onTabGoods(goods, 'minus')" class="product-icon-minus"
									v-if="goods._cartNumber > 0" />
								<view v-if="goods._cartNumber > 0" class="product-handle__number">
									{{ goods._cartNumber }}
								</view>
								<image src="@/uni_modules/cy-cate/static/icon-plus.png"
									@tap.stop="onTabGoods(goods, 'plus')" class="product-icon-plus" />
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部操作栏 -->
		<view class="cart-handle" v-if="showcart">
			<view class="cart-inner">
				<view @click="togglePopup" class="cart-inner__hd">
					<image class="icon-cart" src="@/uni_modules/cy-cate/static/icon-cart.png"></image>
					<view v-if="cart.length" class="cart-inner__number">{{ cartCount }}</view>
				</view>
				<view class="cart-inner__totalPrice">
					<text v-if="cart.length">共计：{{ cartCount }} 个 | {{ cartTypes }} 类</text>
				</view>
				<button class="cart-inner__button" @tap="submitCart">登记</button>
			</view>
		</view>

		<!-- 弹出购物车 -->
		<uni-popup ref="popup" type="bottom" background-color="#fff" border-radius="10px 10px 0 0">
			<view class="cart-info popup">
				<view v-for="(item, index) in cart" :key="index" class="product">
					<image class="product-image" :src="item.thumb || thumb" mode="aspectFill" />
					<view style="width: 100%;">
						<view class="product-name">{{ item.name }}</view>
						<view class="product-desc">
							<text class="product-desc-desc-text" v-if="item.brand">{{ item.brand }}</text>
							<text class="product-desc-desc-text" v-if="item.model">{{ item.model }}</text>
						</view>
						<view style="margin-top: 20rpx; display: flex; justify-content: space-between;">
							<view class="product-price">
								<text class="product-price__value">库存：</text>
								<text class="product-price__value">{{ item.remain_count }}</text>
							</view>
							<view class="product-handle">
								<image @click="onTabGoods(item, 'minus')" class="product-icon-minus"
									src="/uni_modules/cy-cate/static/icon-minus.png"></image>
								<view class="product-handle__number">{{ item._cartNumber }}</view>
								<image @click="onTabGoods(item, 'plus')" class="product-icon-plus"
									src="/uni_modules/cy-cate/static/icon-plus.png"></image>
							</view>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		name: 'CyCate',
		props: {
			categories: {
				type: Array,
				// 修复：将 required: true 改为提供默认值，增强组件健壮性
				default: () => []
			},
			goodsList: {
				type: Array,
				// 修复：将 required: true 改为提供默认值，确保该值始终为数组，从而修复警告
				default: () => []
			},
			activeCategoryId: {
				type: String,
				default: ''
			},
			showcart: {
				type: Boolean,
				default: true
			},
			showplus: {
				type: Boolean,
				default: true
			},
			pageSize: {
				type: Number,
				default: 10
			}
		},
		data() {
			return {
				currentPage: 1,
				cart: [],
				goodsMap: {},
				thumb: '/static/avatar/empty.png',
				scrollLock: false
			}
		},
		watch: {
			goodsList: {
				handler(newVal) {
					const newMap = {}
					// 由于 props 中已设置默认值，newVal 在这里可以确保是一个数组
					newVal.forEach(goods => {
						const cartNumber = this.goodsMap[goods._id]?._cartNumber || 0
						newMap[goods._id] = {
							...goods,
							_cartNumber: cartNumber
						}
					})
					this.goodsMap = newMap
				},
				immediate: true,
				deep: true
			},
			activeCategoryId(newVal) {
				if (newVal) {
					this.currentPage = 1
				}
			}
		},
		computed: {
			filteredGoods() {
				let list = Object.values(this.goodsMap)
				if (this.activeCategoryId) {
					list = list.filter(goods => goods.category_id === this.activeCategoryId)
				}
				return list
			},
			cartCount() {
				return this.cart.reduce((sum, item) => sum + item._cartNumber, 0)
			},
			cartTypes() {
				return this.cart.length
			}
		},
		methods: {
			onTabGoods(goods, type) {
				const target = this.goodsMap[goods._id]

				if (type === 'plus') {
					if (target._cartNumber >= target.remain_count) {
						uni.showToast({
							title: '库存不足',
							icon: 'none'
						})
						return
					}

					const index = this.cart.findIndex(item => item._id === goods._id)
					if (index === -1) {
						this.cart.push({
							...target,
							_cartNumber: 1
						})
					} else {
						this.cart[index]._cartNumber += 1
					}
					target._cartNumber += 1

				} else if (type === 'minus') {
					const index = this.cart.findIndex(item => item._id === goods._id)
					if (index > -1) {
						if (this.cart[index]._cartNumber <= 1) {
							this.cart.splice(index, 1)
						} else {
							this.cart[index]._cartNumber -= 1
						}
					}

					if (target._cartNumber > 0) {
						target._cartNumber -= 1
					}
				}
			},
			goodsclick(goods) {
				this.$emit('goodsclick', goods)
			},
			submitCart() {
				this.$emit('submit', this.cart)

				Object.keys(this.goodsMap).forEach(key => {
					this.$set(this.goodsMap[key], '_cartNumber', 0)
				})

				this.cart = []
				this.$refs.popup.close()
				this.$forceUpdate()
			},
			togglePopup() {
				if (this.cart.length === 0) {
					uni.showToast({
						title: '购物车为空',
						icon: 'none'
					})
					return
				}
				this.$refs.popup.isOpen ? this.$refs.popup.close() : this.$refs.popup.open('bottom')
			},
			handleCategoryTap(category) {
				if (this.activeCategoryId === category._id) {
					return
				}
				this.$emit('category-click', category)
			},
			handleScrollToLower() {
				if (this.scrollLock) return
				this.scrollLock = true
				this.$emit('scrolltolower')
				setTimeout(() => {
					this.scrollLock = false
				}, 500)
			}
		}
	}
</script>

<style lang="scss">
	@import './cy-cate.scss';
</style>